package com.xuecheng.media.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.po.MediaProcess;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.minio.MinioClient;
import io.minio.RemoveObjectsArgs;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Component
@Slf4j
public class SampleJob {
    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MinioClient minioClient;
    private String bucket_name = "video";

    /**
     * 处理上传失败的分块文件
     */
    @XxlJob("processTimeOutVoide")
    public void processTimeOutVoide() {
        log.info("处理上传失败的分块文件");
        LambdaQueryWrapper<MediaProcess> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MediaProcess::getStatus, "3");
        //获取所有未处理数据
        List<MediaProcess> mediaProcesses = mediaProcessMapper.selectList(wrapper);
        //遍历未处理的数据
        mediaProcesses.forEach(i -> {
            //删除1小时未处理的文件
            Duration between = Duration.between(i.getCreateDate(), LocalDateTime.now());
            log.info("该数据多长时间未处理:{}", between.toHours());
            if (between.toHours() >= 1 || between.toDays() >= 1) {
                //删除minio中的文件
                List<DeleteObject> deleteObjects = Stream.iterate(0, j -> ++j).limit(i.getChunkNum()).map(j -> new DeleteObject(i.getFilePath().concat("/chunk").concat(Integer.toString(j)))).collect(Collectors.toList());
                RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(bucket_name).objects(deleteObjects).build();
                Iterable<io.minio.Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
                //必须遍历迭代器才能成功删除
                results.forEach(r -> {
                    DeleteError deleteError = null;
                    try {
                        deleteError = r.get();
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.debug("清除分块文件失败");
                    }
                });
                //将数据库中的文件标为已处理
                MediaProcess mediaProcess = i;

                mediaProcess.setStatus("2");
                mediaProcessMapper.updateById(mediaProcess);
            }
        });
    }
}
